const express = require('express')
const goodsRouter = express.Router()

const goodsList = [
    {id:1001,name:'回锅肉',price:18.89,num:10},
    {id:1002,name:'鱼香肉丝',price:12.59,num:11},
    {id:1003,name:'红烧排骨',price:28.88,num:12},
]
/**
 * 商品列表
 */
goodsRouter.get('/goods/list',(req,res)=>{
    res.send({
        code:1,
        list:goodsList
    })
})



/**
 * 商品添加
 */
goodsRouter.get('/goods/add',(req,res)=>{
    //1. 接收商品数据
    //2. 添加商品到数组
    //3. 响应添加成功
    const id = req.query.id
    const name = req.query.name
    const price = req.query.price
    const num = req.query.num

    goodsList.push({
        id,
        name,
        price,
        num
    })

    res.send({
        code:1,
        message:'添加商品成功'
    })
})


/**
 * 商品删除
 * 
 */
goodsRouter.get('/goods/delete',(req,res)=>{
    //1.接收删除商品id
    //2.删除数组中商品
    //3.响应删除成功
    const id = req.query.id // id=1001
    const index = goodsList.findIndex(item=>item.id == id) //遍历数组查找满足条件元素的索引号

    goodsList.splice(index,1)
    
    res.send({
        code:1,
        message:'删除商品成功'
    })
})



module.exports = {
    goodsRouter
}